//
// Created on 6/3/25.
//
// Node APIs are not fully supported. To solve the compilation error of the interface cannot be found,
// please include "napi/native_api.h".

#include "trackballManipulator.h"
#include "render/Event.h"
#include <arkui/native_type.h>
TrackballManipulator::TrackballManipulator(int w, int h) {
    m_Trackball = std::make_shared<Trackball>();
    m_Trackball->setWindowSize(w, h);
    m_Trackball->setRadius(1.9);
}
TrackballManipulator::~TrackballManipulator() {}

glm::mat4 TrackballManipulator::GetMatrix() { return m_Trackball->getRotationMatrix(); }



void TrackballManipulator::handle(std::shared_ptr<Event> event) {
    auto mouseEvent = dynamic_cast<MouseEvent *>(event.get());
    if (mouseEvent) {
        if (mouseEvent->button == EventButton::LEFT && mouseEvent->action == EventAction::MOUSE_PRESS) {
            m_Trackball->startDrag(mouseEvent->x, mouseEvent->y);
        }
        if (mouseEvent->button == EventButton::LEFT && mouseEvent->action == EventAction::MOUSE_MOVE) {
            m_Trackball->drag(mouseEvent->x, mouseEvent->y);
        }
    }
    auto touchEvent = dynamic_cast<TouchEvent *>(event.get());
    if (touchEvent) {
        if(touchEvent->pointCount==2 && touchEvent->action ==EventAction::TOUCH_DOWN){
//            m_Trackball->startDrag(touchEvent->x, touchEvent->y);
            Point p1=touchEvent->points[0];
            Point p2=touchEvent->points[1];
            float dist = std::sqrt(std::pow(p1.x()-p2.x(),2)+std::pow(p1.y()-p2.y(),2));
            m_PreDist=dist;
        }else
        if(touchEvent->pointCount==2 && touchEvent->action ==EventAction::TOUCH_MOVE){
            Point p1=touchEvent->points[0];
            Point p2=touchEvent->points[1];
            float dist = std::sqrt(std::pow(p1.x()-p2.x(),2)+std::pow(p1.y()-p2.y(),2));
            m_scale = dist-m_PreDist>0?m_scale*0.99:m_scale*1.01;
            m_scale=m_scale<0.1?0.1:m_scale;
            m_scale=m_scale>1?1:m_scale;
            m_Trackball->setDragging(false);
        }else
        if (touchEvent->action == EventAction::TOUCH_DOWN) {
            m_Trackball->startDrag(touchEvent->x, touchEvent->y);
        }else
        if (touchEvent->action == EventAction::TOUCH_MOVE) {
            m_Trackball->drag(touchEvent->x, touchEvent->y);
        }
    }
}
